<template>
    <basic-container>
        <avue-crud :option="option"
                   :data="data"
                   ref="crud"
                   v-model="form"
                   :table-loading="loading"
                   :permission="permissionList"
                   @selection-change="selectionChange"
                   @row-del="rowDel"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   :page="page"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">

            <template slot-scope="{row}" slot="statusShow">
                <el-switch @change="rowSwitchChange(row)" v-model="row.statusShow"></el-switch>
            </template>

            <template slot="search">
                <el-col :span="12">
                    <el-form-item label="创建时间" style="display: inline-block;width: 50%;">
                        <el-date-picker placeholder="开始时间" value-format="yyyy-MM-dd" v-model="beginTime" type="date"
                                        size="mini">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="至" label-width="40px" style="display: inline-block;width: 50%;">
                        <el-date-picker placeholder="结束日期" @change="getTime" value-format="yyyy-MM-dd" v-model="endTime"
                                        type="date" size="mini">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </template>

            <template slot-scope="scope" slot="menu">
                <el-button icon="el-icon-view" type="text" size="mini" @click="getDetail(scope.row)" v-has="'/mall-cloud-cms/cmsComment/list'">查看</el-button>
                <el-button icon="el-icon-edit" type="text" size="mini" @click="reply(scope.row)" >回复</el-button>
            </template>
            <template slot-scope
                      slot="menuLeft">
                <el-button type="primary"
                           icon="el-icon-plus"
                           size="small"
                           plain
                           class="addBtn"
                           @click="allDelete" v-has="'/mall-cloud-cms/cmsComment/removeAll'">批量删除
                </el-button>
            </template>
        </avue-crud>

        <el-drawer title="回复" :visible.sync="replyDialogVisible" :wrapperClosable="false" :close-on-press-escape="false"
                   :show-close="false" size="70%" @close="closeDialog">
            <el-form :model="replyComment" :rules="replyCommentRules" ref="replyCommentRef" label-width="120px"
                     class="demo-ruleForm">

                <el-form-item prop="content" style="width: 50%;display: inline-block;">
                    <editor v-if="replyDialogVisible" @getContent="getContentAddForm" :albumCode="albumCode"></editor>
                </el-form-item>


                <el-form-item label="是否匿名" prop="anonymous" style="width: 50%;">
                    <el-select v-model="replyComment.anonymous" placeholder="请选择">
                        <el-option
                                v-for="item in optionsSelect"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div style="margin: 50px auto;">
                <div style="width:200px;margin: 0px auto;">
                    <el-button type="primary" @click="replyCommentData" :loading="replyCommentLoad" size="mini" v-has="'/mall-cloud-cms/cmsComment/replyComment'">发 表
                    </el-button>
                    <el-button @click="closeDialog" size="mini">取 消</el-button>
                </div>
            </div>
        </el-drawer>


        <el-drawer title="详情" :visible.sync="dialogTableVisible" size="70%">
            <avue-form ref="obj"
                       v-model="obj"
                       :option="optionView">

                <template slot="content">
                    <editor v-if="dialogTableVisible"
                            @getContent="getAddContent"
                            prop="content"
                            :cabackcontent="obj.content"
                            :albumCode="albumCode"
                    ></editor>
                </template>

                <template slot="menuForm">
                    <el-button size="mini" @click="cancel()">取 消</el-button>
                </template>
            </avue-form>
        </el-drawer>

    </basic-container>
</template>

<script>
    import {
        getList,
        remove,
        removeAll,
        update,
        add,
        replyComment,
        getDetail,
    } from "@/api/cms/cmsComment";

    import {
        addFocus,
        deleteFocus
    } from "@/api/cms/cmsFocus";

    import {mapGetters} from "vuex";
    import editor from '@/components/editor/richTextEditor'
    import {setRoles} from "../../api/admin/mgr";

    var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
    export default {
        data() {
            return {
                optionsSelect: [{
                    value: 0,
                    label: '不匿名'
                }, {
                    value: 1,
                    label: '匿名'
                }],
                albumCode:"pic_root",
                currentId: '',
                currentCommentType: 2,    //2，对评论进行评论
                isLike: false,
                form: {},
                replyComment: {},
                query: {},
                obj:{},
                loading: true,
                replyDialogVisible: false,
                dialogTableVisible:false,
                isCommentOrCancel:false,//是否在“抽屉里发表过评论了”
                currentScore:0, //当前评论给出的评分
                albumCode: "pic_root",
                replyCommentLoad: false,
                rolesTree: [],
                rolesKeys: [],
                idList: [],
                box: false,
                beginTime: '',
                endTime: '',
                commentMain: '',
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                option: {
                    searchBtn: true,
                    size: 'mini',
                    tip: false,
                    border: true,
                    index: false,
                    viewBtn: false,
                    addBtn: false,
                    editBtn: false,
                    selection:true,
                    rowKey: 'id',
                    height: 'auto',
                    // calcHeight: 380,
                    dialogType: 'drawer',
                    menuWidth: 200,
                    searchMenuSpan:6,
                    column: [
                        {
                            label: "被评论主体类型",
                            prop: "commentType",
                            fixed: true,
                            type: "select",
                            dicData: Dict.CMS_COMMENT_TYPE,
                            search: true,
                            searchLabelWidth:130,
							searchSpan: 8,
                        },
                        {
                            label: "评分",
                            prop: "score",
                            fixed: true,
                        },
                        {
                            label: "是否显示",
                            prop: "statusShow",
                            fixed: true,
                            type: 'select',
                            dicData: Dict.CMS_SHOW,
                            slot: true
                        },
                        {
                            label: "评论数",
                            prop: "commentCount",
                            fixed: true,
                        },
                        {
                            label: "点赞数",
                            prop: "focousCount",
                            fixed: true,
                        },
                        {
                            label: "评论时间",
                            prop: "addTime",
                            fixed: true,
                            rules: [{
                                required: true,
                                message: "请输入创建时间",
                                trigger: "blur"
                            }]
                        },
                    ]
                },
                optionView: {
                    size: "samll",
                    submitBtn: false,
                    emptyBtn: false,
                    menuPostion: 'center',
                    // calcHeight: 380,
                    menuWidth: 300,
                    labelWidth: 130,
                    border: true,
                    index: false,
                    selection: true,
                    viewBtn: false,
                    rowKey: 'id',
                    height: 'auto',
                    column: [
                        {
                            label: "评论内容",
                            prop: "content",
                            formslot: true,
                            fixed: true,
                            disabled:true,
                            value:false,
                        }
                    ]
                },
                replyCommentRules: {
                    content: [{
                        required: true,
                        message: "请输入评论内容",
                        trigger: "blur"
                    },],
                    anonymous: [{
                        required: true,
                        message: "请选择是否匿名",
                        trigger: "blur"
                    },]
                },
                data: []
            };
        },
        components: {
            editor,
        },
        computed: {
            ...mapGetters(["permission", 'userInfo']),
            permissionList() {
                return {
                    delBtn: this.vaildData(this.permission["/mall-cloud-cms/cmsComment/delete"], false),
                };
            },
        },
        methods: {

            getAddContent(val){
                this.obj.content = val;
            },

            getTime() {
                if (this.beginTime > this.endTime) {
                    this.$message({
                        type: "error",
                        message: "结束时间不能小于开始时间"
                    });
                    this.endTime = ''
                }
            },
            rowSave(row, loading, done) {
                row.position = row.positionIds;
                row.deptName = row.$deptId;
                row.repassword = row.password;
                add(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            rowUpdate(row, index, loading, done) {
                row.position = row.positionIds;
                update(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            //监控多选点击事件
            selectionChange(row) {
                var idList = []
                if (row.length > 0) {
                    for (let item of row) {
                        idList.push(item.id)
                    }
                    this.idList = idList
                }
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            searchReset() {
                this.idList = []
                this.query = {};
                this.beginTime = ''
                this.endTime = ''
                this.onLoad(this.page);
            },
            searchChange(params,done) {
                this.idList = [];
                this.page.currentPage = 1;
                params.beginTime = this.beginTime;
                params.endTime = this.endTime;
                this.query = params;
                this.onLoad(this.page, params,done);
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page);
            },
            allDelete() {
                removeAll(this.idList).then(res => {
                    if (res.data.success) {
                        this.onLoad(this.page, this.params);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                }, error => {
                    console.log(error);
                });
            },
            onLoad(page, params = {},done) {
                if (this.$route.query.id && this.isCommentOrCancel == false) {
                    //说明从其他页面跳转过来的
                    // 所以根据他传的id（只有是从文章那里跳转过来的所以类型一定是文章类型），所以可以直接打开评论框
                    this.query.commontId = this.$route.query.id;
                    this.query.commentType = 1;
                    this.replyDialogVisible = true;
                    this.currentCommentType = 1;
                    this.currentId = this.$route.query.id;
                }
                else{
                    this.query.commontId = "";
                }
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    if(done){
                        done();
                    }
                    this.loading = false;
                    const data = res.data;
                    this.page.total = data.count;
                    this.data = data.data;
                });
                console.log(Dict)
            },

            rowSwitchChange(row) {
                if (row.statusShow) {
                    update(row.id, 0);
                } else {
                    update(row.id, 1);
                }
            },

            getContentAddForm(val) {
                this.replyComment.content = val;
            },

            getDetail(row){
                getDetail(row.id).then(res => {
                    if(res.data.code == 200){
                        if(res.data.data.length>0){
                            this.obj = res.data.data[0];
                        }
                        this.dialogTableVisible = true;
                    }else{
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        });
                        return;
                    }
                });
            },

            reply(row) {
                // 点击回复就是对评论进行回复
                this.replyDialogVisible = true;
                this.currentCommentType = 2
                this.currentId = row.id;
            },
            //Integer commentType,Long commentId,String content,Integer score,Integer anonymous
            replyCommentData() {
                this.isCommentOrCancel = true;
                this.replyCommentLoad = true;
                console.log(typeof this.replyComment.content);
                if(typeof this.replyComment.content =='undefined'){
                    this.replyCommentLoad = false;
                    this.$message({
                        type: "error",
                        message: "请输入评价内容"
                    });
                    return;
                }
                else {
                    let test=this.replyComment.content.replace(/<\/?.+?>/g,"");
                    let tempContent=test.replace(/\s*/g,"");
                    console.log(tempContent);
                   if(tempContent.length==0){
                       this.replyCommentLoad = false;
                       this.$message({
                           type: "error",
                           message: "请输入评价内容"
                       });
                       return;
                   }
                   console.log(this.replyComment.content)
                }
                console.log(typeof this.replyComment.anonymous);
                if(typeof this.replyComment.anonymous != "string" && typeof this.replyComment.anonymous!='undefined'){
                    replyComment(this.currentCommentType, this.currentId, this.replyComment.content,this.replyComment.anonymous,this.currentScore).then(res => {
                        if (res.data.code == 200) {
                            this.replyCommentLoad = false;
                            this.$message({
                                type: "success",
                                message: "发表成功!"
                            });
                            this.replyDialogVisible = false;
                            this.replyComment.anonymous = '';
                            this.onLoad(this.page);
                        }
                        else {
                            this.replyCommentLoad = false;
                            this.$message({
                                type: "error",
                                message: "发表评论失败"
                            });
                        }
                    }, error => {
                        this.replyCommentLoad = false;
                    });
                }
                else{
                    this.replyCommentLoad = false;
                    this.$message({
                        type: "error",
                        message: "请选择是否匿名"
                    });
                    return;
                }

            },
            closeDialog() {
                this.replyDialogVisible = false;
                this.$route.query.id ="";
                this.currentScore=0;
                this.query = {};
                this.replyComment.anonymous = '';
                this.replyComment.content = '';
                this.onLoad(this.page);
            },
            getLike(row) {
                this.isLike = true;
                addFocus(this.currentCommentType, row.id).then(res => {
                    if (res.data.code == 200) {
                        this.onLoad(this.page);
                    }
                    else {
                        this.$message({
                            type: "error",
                            message: "点赞失败"
                        });
                    }
                }, error => {
                });
            },
            getNotLike(row) {
                this.isLike = false;
                deleteFocus(this.currentCommentType, row.id).then(res => {
                    if (res.data.code == 200) {
                        this.onLoad(this.page);
                    }
                    else {
                        this.$message({
                            type: "error",
                            message: "点赞失败"
                        });
                    }
                }, error => {
                });
            },
            cancel() {
                this.dialogTableVisible = false;
            }

        }
    };
</script>

<style>
</style>
